package com.qb.mobile;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.qb.mobile.R;
import com.qb.Contants;
import com.qb.mobile.adapter.SystemPhonebookAdapter;
import com.qb.mobile.core.actionbar.Action;
import com.qb.mobile.core.actionbar.ActionBar;
import com.qb.mobile.core.actionbar.IntentAction;
import com.qb.mobile.manager.ContactsSystem;
import com.qb.mobile.model.Phonebook;

/**
 * @author <a href="mailto:dangcongthanhtrung@gmail.com">dangtrung</a>
 * 
 *         SystemPhonebookList.java class
 * 
 */
public class SystemPhonebookList extends Activity {

	private List<Phonebook> listOfPhonebook;
	private ListView list;
	private ActionBar actionBar;
	private String ids = "";
	private SystemPhonebookAdapter systemPhonebookAdapter = null;
	Intent intent;
	
	public String getIds() {
		return ids;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.system_phone_book_list);
		initListView();
		initActionBar();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private void initListView() {
		ids = getIntent().getStringExtra("Ids");
		listOfPhonebook = new ArrayList<Phonebook>();
		list = (ListView) findViewById(R.id.system_phone_book_list);
		systemPhonebookAdapter = new SystemPhonebookAdapter(this, listOfPhonebook);
		new RetrieveRssFeeds().execute();

	}

	private void initActionBar() {
		actionBar = (ActionBar) findViewById(R.id.actionbar);
		
		Action homeAction = new IntentAction(this, new Intent(this, PhonebookList.class),
				R.drawable.ic_home_default, false, true);
		actionBar.setHomeAction(homeAction);

		Action exportAction = new IntentAction(this, exportIntent(this), 
				R.drawable.ic_export_default, true, false);
		actionBar.addAction(exportAction);
	}
	
	private Intent exportIntent(Context context) {
		intent = new Intent(this, PhonebookList.class);
		//String values = PreferenceUtils.getPrefeByClear(this, Contants.SYSTEM_PHONE_BOOK);
		intent.putExtra(Contants.SYSTEM_PHONE_BOOK, "");
		return intent;
	}

	private boolean hasImported(String id) {
		String[] arrId = ids.split(",");
		for (int i = 0; i < arrId.length; i++) {
			if (id.equalsIgnoreCase(arrId[i]))
				return true;
		}
		return false;
	}
	
	private void updatePhonebookFromSystemPhonebookList() {
		listOfPhonebook = new ArrayList<Phonebook>();
		List<Phonebook> list = new ArrayList<Phonebook>();
		ContactsSystem contact = new ContactsSystem(this, list);
		list = contact.newContactList();

		Iterator<Phonebook> it = list.iterator();
		while (it.hasNext()) {
			Phonebook phoneBook = (Phonebook) it.next();
			if (!hasImported(phoneBook.getId())	&& phoneBook.getPhones() != null) {
				listOfPhonebook.add(phoneBook);
			}
		}
	}

	private void changeTitleBar() {
		actionBar.setTitle(getResources().getString(R.string.activity_title_contact_import));
		if (listOfPhonebook.size() <= 0) {
			TextView txtEmpty = (TextView) findViewById(R.id.sys_txt_all_contact_import);
			txtEmpty.setVisibility(1);
		}
		actionBar.requestFocus();
	}
	
	/**
	 * @author <a href="mailto:dangcongthanhtrung@gmail.com">dangtrung</a>
	 * 
	 *         RssMain.java class
	 */
	private class RetrieveRssFeeds extends AsyncTask<Void, Void, Void> {
		private ProgressDialog progress = null;

		@Override
		protected Void doInBackground(Void... params) {
			Context context = getApplicationContext();
			updatePhonebookFromSystemPhonebookList();
			systemPhonebookAdapter = new SystemPhonebookAdapter(context, listOfPhonebook);
			return null;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPreExecute() {
			String load_text = getResources().getString(R.string.load_text);
			progress = ProgressDialog.show(SystemPhonebookList.this, null,
					load_text);
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Void result) {
			list.setAdapter(systemPhonebookAdapter);
			list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			list.setOnItemClickListener(contactClickedHandler);
			changeTitleBar();
			progress.dismiss();
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			super.onProgressUpdate(values);
		}
	}
	
	private OnItemClickListener contactClickedHandler = new OnItemClickListener() {
		
	    public void onItemClick(AdapterView<?> a, View v, int position, long id)
	    {
	    	SparseBooleanArray checkedItems = new SparseBooleanArray();
			checkedItems.clear();
			checkedItems = list.getCheckedItemPositions();
			String selectedChild = "";
		    for (int i = 0; i < checkedItems.size(); i++)
		    {
			    //added if statement to check for true. The SparseBooleanArray
			    //seems to maintain the keys for the checked items, but it sets
			    //the value to false. Adding a boolean check returns the correct result.                    
		        if(checkedItems.valueAt(i) == true){
		        	String idContact = listOfPhonebook.get(checkedItems.keyAt(i)).getId();
		        	if (selectedChild.length() > 0) {
		        		selectedChild += "," + idContact;
					} else {
						selectedChild += idContact;
					}
		        }
		    } 
		    intent.putExtra(Contants.SYSTEM_PHONE_BOOK, selectedChild);
	    }
	};
}
